import socket
# from net.msg_handle import msg_handle
from net.msg_handle import *
from warnings import warn
import sys
from bdtime import log_config_dc
import logging
log = logging.getLogger("my_env")
logging.basicConfig(**log_config_dc.complex)
log.setLevel(logging.INFO)
# from tools.my_log import my_prt as print
# from tools.my_log import log


class _Flag:
    EXIST_FLAG = False


Flag = _Flag()


def main(debug_model=False):

    # Create a TCP/IP socket
    server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    # server = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
    # server.bind("/tmp/test.sock")

    # Enable port reuse on Windows
    if sys.platform.startswith("win"):
        server.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
        # server.setsockopt(socket.SOL_SOCKET, socket.SO_EXCLUSIVEADDRUSE, 1)
        pass
    # Enable port reuse on Unix
    else:
        server.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)

    # Bind the socket to a port
    # server_address = ('localhost', 8888)
    server_address = ('0.0.0.0', 8888)

    if 0:
        from shells.sshKillOldProcessing import run as kill_old_processing
        kill_old_processing(port=server_address[-1])

    server.bind(server_address)

    print(f'--- 正在监听 {server_address}')

    # Listen for incoming connections
    server.listen(1)

    while True:
        # print(f'Flag.EXIST_FLAG --- {Flag.EXIST_FLAG}')

        if Flag.EXIST_FLAG:
            break

        # Wait for a connection
        connection, client_address = server.accept()
        # connection.getpeername()
        # connection.getsockname()
        if msg_handle.client_connection is None:
            msg_handle.client_connection = connection

        print(f' --- client_address: {client_address} | client_connection: {connection}')

        try:
            # Receive data in small chunks and print it
            while True:
                # tt.sleep(0.001)
                if Flag.EXIST_FLAG:
                    connection.close()
                    msg_handle.client_connection = None
                    break

                try:
                    data = MessageController.recv_message(connection)
                    if data is None:
                        print(f'=== 连接已关闭, client_address: {client_address}')
                        break
                except Exception as e:
                    msg_handle.MsgClose()
                    MessageController.close(connection)
                    # raise e
                    log.error(e)
                    continue
                    # break

                # data = connection.recv(1024)
                if data:
                    # print(f' --- data[{len(data)}]:\n{data}')
                    # if len(data) not in [68, 69, 70]:
                    #     print(f'*** 数据长度超出4位? data[{len(data)}]: {data}')

                    if debug_model:
                        msg_str = data.decode(encoding)
                        print('--- 222222 received data: ', msg_str)

                        MessageController.send_message(connection, data)
                        # connection.send(data)
                    else:
                        """
                        数据处理
                        """
                        # data: bytes
                        msg_str = data.decode(encoding)
                        # print('--- received data: ', msg_str)

                        use_try_except_run = 0      # 正式版再用, 避免报错而中断服务
                        if use_try_except_run:
                            try:
                                msg_handle.run(data)
                            except Exception as e:
                                log.error(e)
                        else:
                            msg_handle.run(data)
                else:
                    # No more data, close the connection
                    break
        finally:
            # Clean up the connection
            connection.close()
            msg_handle.client_connection = None


if __name__ == '__main__':
    main()


